import requests
import json
import os
from notify import send  # 青龙通知模块
##cron: 19 9 * * *
##new Env("IKUUU")

# 配置参数
HOSTS = ["ikuuu.org", "ikuuu.club", "ikuuu.de", "ikuuu.cc"]  # 支持多个HOST
TITLE = "IKUUU签到"  # 通知标题

def get_env_vars():
    accounts = os.getenv('IKUUU')
    
    if not accounts:
        return None
    
    account_list = accounts.split('&')
    parsed_accounts = []
    
    for account in account_list:
        if '#' not in account:
            continue
        email, passwd = account.split('#', 1)
        parsed_accounts.append({
            'email': email.strip(),
            'passwd': passwd.strip()
        })
    
    return parsed_accounts

def login(host, email, passwd):
    url = f"https://{host}/auth/login"
    
    headers = {
        "Host": host,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Referer": f"https://{host}/auth/login",
    }
    
    data = {
        "email": email,
        "passwd": passwd,
        "code": "",
        "remember_me": "on"
    }
    
    try:
        res = requests.post(url, headers=headers, data=data, timeout=10)
        res.encoding = 'utf-8'
        
        if res.status_code != 200:
            return None, f"HTTP状态码: {res.status_code}"
            
        try:
            result = res.json()
            if isinstance(result, dict):
                if result.get('ret') == 1:
                    return host, res.cookies.get_dict(), result.get('msg', '登录成功')
                else:
                    return None, None, result.get('msg', '登录失败')
            return None, None, "返回结果格式异常"
        except json.JSONDecodeError:
            return None, None, "返回非JSON数据"
        
    except requests.exceptions.RequestException as e:
        return None, None, f"请求异常: {str(e)}"

def check_in(host, cookies):
    url = f"https://{host}/user/checkin"
    
    headers = {
        "Host": host,
        "Accept": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": f"https://{host}/user",
    }
    
    try:
        res = requests.post(url, headers=headers, cookies=cookies, timeout=10)
        res.encoding = 'utf-8'
        
        if res.status_code != 200:
            return f"签到失败，HTTP状态码: {res.status_code}"
            
        try:
            result = res.json()
            if isinstance(result, dict):
                if result.get('ret') == 1:
                    return result.get('msg', '签到成功')
                else:
                    return result.get('msg', '签到失败')
            return "签到返回结果格式异常"
        except json.JSONDecodeError:
            return "签到返回非JSON数据"
            
    except requests.exceptions.RequestException as e:
        return f"签到请求异常: {str(e)}"

def try_multiple_hosts(email, passwd):
    for host in HOSTS:
        host, cookies, login_msg = login(host, email, passwd)
        if cookies:
            return host, cookies, login_msg
    return None, None, "所有HOST尝试失败"

def main():
    accounts = get_env_vars()
    if not accounts:
        send(TITLE, "未找到IKUUU环境变量，请检查!")
        return
    
    results = []
    total = len(accounts)
    success = 0
    
    for account in accounts:
        email = account['email']
        passwd = account['passwd']
        
        # 尝试多个HOST登录
        host, cookies, login_msg = try_multiple_hosts(email, passwd)
        
        if cookies:
            # 签到
            checkin_msg = check_in(host, cookies)
            results.append(f"账号: {email}\n使用HOST: {host}\n登录: {login_msg}\n签到: {checkin_msg}")
            success += 1
        else:
            results.append(f"账号: {email}\n登录失败: {login_msg}")
    
    # 汇总通知
    summary = f"共处理 {total} 个账号，成功 {success} 个\n可用HOST: {', '.join(HOSTS)}\n\n" + "\n\n".join(results)
    send(TITLE, summary)

if __name__ == "__main__":
    main()